import subprocess
import os

def save_pip_freeze(output_file="requirements.txt"):
    """
    执行 `pip freeze` 命令并将结果保存到指定文件
    
    参数:
        output_file: 输出文件名，默认为 requirements.txt
    """
    try:
        # 执行 pip freeze 命令
        result = subprocess.run(
            ["pip", "freeze"],
            capture_output=True,
            text=True,
            check=True
        )
        
        # 获取当前脚本所在目录
        current_dir = os.getcwd()
        file_path = os.path.join(current_dir, output_file)
        
        # 写入文件
        with open(file_path, "w") as f:
            f.write(result.stdout)
            
        print(f"已成功将 pip 包列表保存到: {file_path}")
        
    except subprocess.CalledProcessError as e:
        print(f"执行 pip freeze 时出错: {e.stderr}")
    except Exception as e:
        print(f"保存文件时出错: {e}")

if __name__ == "__main__":
    save_pip_freeze()  # 默认保存为 requirements.txt
    # 或者指定其他文件名: save_pip_freeze("my_packages.txt")


